package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.search.dao.ESManagerMapper;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.ESManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class ESManagerServiceImpl implements ESManagerService {

    @Autowired
    private SkuFeign skuFeign;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    private ESManagerMapper esManagerMapper;
    //创建索引库
    @Override
    public void creatMappingAndIndex() {
        elasticsearchTemplate.createIndex(SkuInfo.class);
        elasticsearchTemplate.putMapping(SkuInfo.class);
    }

    //导入全部Sku集合到索引库
    @Override
    public void importAll() {
        //查询sku集合
        List<Sku> list = skuFeign.findSkuListBySpuId("all");
        //如果集合内没有数据则抛出异常
        if (list == null || list.size() <= 0) {
            throw  new RuntimeException("没有数据可以导入到索引库中");
        }
        //将查询出来的list集合转换成json字符串
        String skuListJson = JSON.toJSONString(list);
        //再将json字符串映射到es索引库对应的实体类
        List<SkuInfo> skuInfoList = JSON.parseArray(skuListJson, SkuInfo.class);
        //将spec数据封装到map内
        for (SkuInfo skuInfo : skuInfoList) {
            String spec = skuInfo.getSpec();
            Map map = JSON.parseObject(spec, Map.class);
            skuInfo.setSpecMap(map);
        }
        esManagerMapper.saveAll(skuInfoList);
    }
    //根据spuId导入对应的sku数据
    @Override
    public void importDataBySpuId(String spuId) {
        List<Sku> skuList = skuFeign.findSkuListBySpuId(spuId);

        if (skuList == null || skuList.size() <= 0) {
            throw new RuntimeException("没有数据可以导入到索印库中");
        }
        String skuListJson = JSON.toJSONString(skuList);
        List<SkuInfo> skuInfoList = JSON.parseArray(skuListJson, SkuInfo.class);

        for (SkuInfo skuInfo : skuInfoList) {
            String spec = skuInfo.getSpec();
            Map map = JSON.parseObject(spec, Map.class);
            skuInfo.setSpecMap(map);
        }
        esManagerMapper.saveAll(skuInfoList);
    }
    //根据spuId删除对应的sku数据
    @Override
    public void deleteDataBuSpuId(String spuId) {
        List<Sku> skuList = skuFeign.findSkuListBySpuId(spuId);
        if(skuList==null||skuList.size()<=0){
            throw new RuntimeException("没有数据可以删除");
        }
        for (Sku sku : skuList) {
            esManagerMapper.deleteById(Long.parseLong(sku.getId()));
        }
    }


}
